package com.fs.book.service.impl;

import com.fs.book.entity.Book;
import com.fs.book.entity.CartItem;
import com.fs.book.entity.User;
import com.fs.book.exception.BookBaseException;
import com.fs.book.mapper.BookMapper;
import com.fs.book.mapper.UserMapper;
import com.fs.book.service.BookService;
import com.fs.book.vo.BookVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("bookService")
@Transactional
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private UserMapper userMapper;

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public Book queryById(Integer bid) throws Exception {
        if (bid == null) {
            throw new BookBaseException("id不能为空");
        }
        return bookMapper.selectById(bid);
    }

    public boolean addBook(Book book) throws Exception {
        return bookMapper.insert(book) > 0;
    }

    @Override
    public List<Book> queryAll() throws Exception {
        return bookMapper.selectAll();
    }

    @Override
    public Page<Book> queryByPage(BookVO bookVO) throws Exception {
        // 开启分页查询
        String orderBy = bookVO.getOrderColumn() + " " + bookVO.getOrderType();
        Page<Book> pages = PageHelper.startPage(bookVO.getPageIndex(), 5, orderBy);
        bookMapper.selectByPage(bookVO);
        return pages;
    }

    @Override
    public void addToCart(Book book, Integer quantity, User currentUser) {
        // 获取当前用户的购物车项，如果不存在则创建一个新的购物车项
        CartItem cartItem = userMapper.findByBidAndUid(book.getBid(), currentUser.getUid());

        if (cartItem == null) {
            cartItem = new CartItem();
            cartItem.setBid(book.getBid());
            cartItem.setUid(currentUser.getUid());
            cartItem.setQuantity(quantity);
            cartItem.setPrice(book.getPrice());
            cartItem.setImageB(book.getImageB());
            userMapper.saveCartItem(cartItem);  // 假设 userMapper 有保存购物车项的方法
        } else {
            // 如果购物车项已存在，则更新数量
            cartItem.setQuantity(cartItem.getQuantity() + quantity);
            userMapper.updateCartItem(cartItem);  // 假设 userMapper 有更新购物车项的方法
        }
    }

}
